<template>
  <div class="page-box">
    <!-- 筛区域 -->
    <div class="search-box">
      <!-- :inline="true" 表单在一行显示 -->
      <el-form size="mini" :inline="true" class="demo-form-inline">
        <el-form-item label="广告图描述">
          <el-input v-model.trim="query.advimgdesc" placeholder="请输入广告位名称" />
        </el-form-item>

        <el-form-item label="广告图位置">
          <el-select v-model="query.advimgpos" placeholder="请选择广告位" @change="changename">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item"
              :value="item"
            />

          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 工具条区域 -->
    <div class="tabbar-box">
      <el-row type="flex" justify="space-between">
        <div>
          <el-button plain type="primary" icon="el-icon-plus" size="mini" @click="openDilog('add')">新增</el-button>
          <el-button plain type="warning" icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
        </div>
        <div>
          <el-button icon="el-icon-arrow-down" size="mini" circle />
          <el-button icon="el-icon-refresh" size="mini" circle />
          <el-button icon="el-icon-menu" size="mini" circle />
        </div>
      </el-row>
    </div>
    <!-- 表格区域 -->
    <div class="table-box">
      <el-table
        ref="multipleTable"
        border
        :data="list"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="#" width="50" />
        <el-table-column prop="advposname" label="广告图位" />
        <el-table-column prop="advimgdesc" label="广告图描述" />
        <el-table-column prop="data" label="广告图">
          <template #default="{row}">
            <img style="width:150px;" :src="'http://124.223.14.236:8060/' + row.advimgsrc" alt="">
          </template>
        </el-table-column>
        <el-table-column prop="advimglink" label="广告图链接" />
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-row type="flex" justify="center">
              <el-button circle type="primary" icon="el-icon-edit" size="mini" @click="openDilog('edit',row.id)" />
              <el-button circle type="danger" icon="el-icon-delete" size="mini" @click="open(row.id)" />
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page">
      <el-row type="flex" justify="end">
        <el-pagination
          background
          :current-page="query.page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="query.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- ! 弹层 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="45%"
      :before-close="handleClose"
    >
      <!-- ! 弹层中的表单  -->
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="margin-left:50px">
        <el-form-item label="广告位" prop="advimgpos">

          <el-select v-model="form.advimgpos" placeholder="请选择">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>

        </el-form-item>
        <el-form-item label="广告图描述" prop="advimgdesc">
          <el-input v-model="form.advimgdesc" type="textarea" placeholder="请输入广告图描述" style="width:400px" />
        </el-form-item>
        <el-form-item label="广告图链接" prop="advimglink">
          <el-input v-model="form.advimglink" placeholder="请输入广告图链接" style="width:400px" />
        </el-form-item>
        <el-form-item label="广告图">
          <el-upload
            ref="upload"
            v-model="form.advimgsrc"
            class="upload-demo"
            action="http://124.223.14.236:8060/"
            :on-success="success"
            :file-list="fileList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAdvImg, getImg, addAdvImg, deleteAdvImg, getAdvImgDetail, editAdvImg } from '@/api/adv/img'
import { getPosition } from '@/api/adv/pos'
// ! 导出
import { exportData } from '@/utils/export'
export default {
  data() {
    return {
      form: {
        advimgdesc: '',
        advimglink: '',
        advimgpos: '',
        advimgsrc: ''
      },
      rules: {
        advimgdesc: [
          { required: true, message: '描述类型必须!', trigger: 'blur' }
        ],
        advimglink: [
          { required: true, message: '链接类型必须!', trigger: 'blur' }
        ],
        advimgpos: [
          { required: true, message: '广告位类型必须!', trigger: 'blur' }
        ]
      },
      // ! 导出数据
      aoa: [],
      list: [],
      query: {
        advimgdesc: '',
        advimgpos: '',
        page: 1,
        limit: 10
      },
      value: '',
      id: '',
      total: 0,
      options: [],
      newid: '',
      List: [],
      dialogVisible: false,
      dialogType: 'add',
      fileList: []
    }
  },
  computed: {
    // ! 修改弹层标题
    dialogTitle() {
      let title = ''
      if (this.dialogType === 'add') title = '添加广告图'
      if (this.dialogType === 'edit') title = '修改广告图'
      return title
    }
  },
  created() {
    this.initData()
    this.getAdvPosition()
  },
  methods: {
    // ! 上传图片
    async success(response, files, fileList) {
      const file = fileList[0].raw
      console.log(file)

      const fd = new FormData()

      fd.append('file', file)
      const res = await getImg(fd)
      this.form.advimgsrc = res.savePath
      console.log(this.form.advimgsrc)
    },
    // !添加&编辑
    async submit() {
      try {
        // ! 兜底校验
        await this.$refs.form.validate()
        // ! 添加
        if (this.dialogType === 'add') {
          this.List.forEach(item => {
            if (item.advposname === this.form.advimgpos) {
              this.newid = item.id
            }
          })
          this.form.advimgpos = this.newid
          await addAdvImg(this.form)
          this.$message.success('添加成功!')
        }
        // ! 编辑
        if (this.dialogType === 'edit') {
          const { id, advimgdesc, advimglink, advimgpos, advimgsrc } = this.form
          await editAdvImg({
            id, advimgdesc, advimglink, advimgpos, advimgsrc
          })
          this.$message.success('修改成功!')
        }
        this.page = 1
        this.initData()
        this.handleClose()
      } catch (error) {
        console.log(error)
      }
    },
    // ! 删除操作
    open(id) {
      this.$confirm('确定删除吗,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // ! 删除请求
        await deleteAdvImg(id)
        this.initData()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // ! 弹层打开
    async openDilog(type, id) {
      this.dialogVisible = true
      this.dialogType = type
      // ! 数据回显
      if (this.dialogType !== 'add') {
        const res = await getAdvImgDetail(id)
        console.log(res)

        this.form = { ...res }
        // ! 图片回显
        const obj = { name: '点击查看详情', url: 'http://124.223.14.236:8060/' + res.advimgsrc }
        if (res.advimgsrc === null) {
          this.fileList = []
        } else {
          this.fileList.push(obj)
        }
      }
    },
    // ! 弹层关闭
    handleClose(done) {
      this.dialogVisible = false
      this.form = {
        advimgdesc: '',
        advimglink: '',
        advimgpos: '',
        advimgsrc: ''
      }
      // ! 重置表单校验
      this.$refs.form.clearValidate()
      // ! 清空文件数据中的数据
      this.fileList = []
      this.$refs.upload.clearFiles()
    },
    // ! 分页
    handleSizeChange(value) {
      this.query.limit = value
      this.query.page = 1
      this.initData()
    },
    handleCurrentChange(value) {
      this.query.page = value
      this.initData()
    },
    // ! 搜索
    async search() {
      this.query.page = 1
      this.query.advimgpos = this.newid

      await this.initData()
      this.query.advimgpos = ''
      this.query.advimgdesc = ''
    },
    // ! 重置
    reset() {
      this.query = {
        advposdesc: '',
        advposname: '',
        page: 1,
        limit: 10
      }
      this.initData()
    },
    // ! 导出
    exportData() {
      this.list.forEach((item, index) => {
        this.aoa.push([index + 1, item.advposname, item.advimgdesc, item.advimgsrc, item.advimglink])
      })
      exportData(this.list, ['#', '广告图位', '广告图描述', '广告图', '广告图链接'], this.aoa)
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    async initData() {
      const res = await getAdvImg(this.query)
      this.list = res.data
      this.total = res.count
    },
    // ! 广告位
    async getAdvPosition() {
      const res = await getPosition()
      console.log(res)

      this.List = res
      const newList = res.map(item => item.advposname)
      this.options = newList
    },
    changename(vlaue) {
      this.List.forEach(item => {
        if (item.advposname === vlaue) {
          this.newid = item.id
        }
      })
    }

  }

}
</script>
<style lang="scss" scoped>
  .page-box {

    margin: 20px;
    padding: 20px;
    background-color: #fff;
    .search-box,.tabbar-box {
      padding-top: 10px;
      height: 50px;
    }
  }
   ::v-deep .el-dialog__header{
   padding: 15px 20px 10px!important;
    border-bottom: 1px solid #e9ecef;
    background-color: #fafafa;
  }

</style>
